<?php 
	if (!defined('IN_OS'))
	{
	    die('Access Denied');
    }
    defineAPI_APP();//定义taobao 相关API常量    
    //API系统参数
	$topParamArr = array(
		'api_key' =>   $_CFG['taobao_app_key'] ,
		'method' => 'taobao.trades.sold.get', //taobao.item.get
		'format' => 'xml',
		'v' => '1.0',
		'timestamp' => date('Y-m-d H:i:s'),
		'session' => $_CFG['taobao_sessionkey'],
	    'nick'    => $_CFG['taobao_user'] 
	);  
	require_once(ROOT_PATH . 'admin/includes/lib_goods.php'); 
	require_once(ROOT_PATH . 'includes/lib_order.php'); 
	
	include_once('lib_top_api/lib_taobao_user.php');      //2.1.1 用户API
	include_once('lib_top_api/lib_taobao_product.php');   //2.1.2 产品API
	include_once('lib_top_api/lib_taobao_itemcat.php');   //2.1.3 类目属性API
	include_once('lib_top_api/lib_taobao_item.php');      //2.1.4 商品API
	include_once('lib_top_api/lib_taobao_taobaoke.php');  //2.1.5 淘宝客API
	include_once('lib_top_api/lib_taobao_trade.php');     //2.1.6 交易API
	include_once('lib_top_api/lib_taobao_traderate.php'); //2.1.7 评价API
	include_once('lib_top_api/lib_taobao_logistic.php');  //2.1.8 物流API
	include_once('lib_top_api/lib_taobao_shop.php');      //2.1.9 店铺API 
	
    include_once('lib_taobao2os.php');   /* TOP与OS转换函数 */  

	
   
    /**
     *  taobao属性图片对应ＯＳ当中的色卡库功能  
     *  处理小图标色卡库的问题
     * */
     function  PropImg2color_lib($goods_id,$iid,$cid){
        global  $db,$os,$topParamArr;
     	$sql="select * from open_tb_PropImg where iid='".$iid."'";  
     	if(! $propimg_id = Check_is_exist('tb_PropImg','iid',$iid,'',"propimg_id" )  ) GetTBOneItem(  $iid );
     	$propimg_rows = $db->getAll($sql);
     	//不存在有两种可能。没有设置sku 或者设置sku并没上传图片 
     	if(!$propimg_rows && !Check_is_exist('tb_sku','iid',$iid)  ) {  //taobao未上传属性小图片.并没有对应的颜色尺码sku
     		$arr=array(
     				'img_name' =>$goods_id.'_默认',
     				'img_code' =>$goods_id.'_000',
     				'img_file' =>Check_is_exist('tb_item','iid',$iid,'','pic_path') ,
     			);
     		OS_InsertIntoTB('color_lib','img_code',$arr);
     		$img_id	=Check_is_exist('color_lib','img_code',$goods_id.'_000','','img_id');
     		$color_id=Check_is_exist('color','color_code','000','','color_id');
     		Update_table_key('goods_color','img_id',$img_id,"goods_id='".$goods_id."' and color_id='".$color_id."'");
     	}elseif ( !$propimg_rows && Check_is_exist('tb_sku','iid',$iid) ){//未上传属性图片但此商品有图片与尺码
     		//没有小图片
     	} 
     	foreach ($propimg_rows as $propimg_row){
	    	$properties = $propimg_row['properties'];
	    	$props = explode(':', $properties );   
	    	if( is_array($props) && $props[1]   ){  //是数组求颜色值
	    		 $sql="select c.color_name,c.color_code,c.color_id from open_tb_guige1 as gg1
						left join open_color as c on c.color_code=gg1.color_code
						where gg1.vid='".$props[1]."' and  gg1.cid='".$cid."'"; 
	    		 $color_row=$db->getRow($sql); 
	    		 $sql="select cl.img_id from open_goods_color as gc 
	    		 	   left join open_color_lib cl on gc.img_id = cl.img_id	
	    		 	   where gc.goods_id ='".$goods_id."' and gc.color_id='".$color_row['color_id'] ."'"; 
	    		 $img_id=$db->getOne($sql);
	    		 if( $color_row && $color_row['color_id'] && $propimg_row['url'] && !$img_id){  //img_id不存在
	    		 	$sql="insert into open_color_lib(img_name,img_file) values('".$goods_id.'_'.$color_row['color_name']."','".$propimg_row['url']."')  ";
	    		  	$db->query($sql);
	    		  	$img_id=$db->insert_id();
	    		  	$sql="update open_color_lib set img_code='".$img_id."' where img_id='".$img_id."' ";
	    		  	$db->query($sql);
	    		  	$sql="update open_goods_color as gc set img_id='".$img_id."'   where gc.goods_id='".$goods_id."' and gc.color_id='".$color_row['color_id']."'";
	    		  	$db->query($sql); 
	    		 }
	    	} 
     	} 
      }  
    /**
     * 处理商品颜色与尺码关系 根据别名向颜色尺码表里插入数量 
     * 
     * */
    function props2guige($goods_id,$props,$prop_alias,$cid){   
	    global  $db,$os; 
	    if(!$props) return ;
		$str='';  
		$have_color = 0; //属性当中不存在颜色
		$have_size = 0;  //属性当中不存在尺码 
		$props = explode(';', $props );   
		foreach ($props as $prop ){
			$prop_t = explode(':', $prop );  
			if( !is_array($prop_t) || !$prop_t[1] ) continue; 
			$sql='select prop_name,name from open_tb_propvalue where vid='.$prop_t[1] ;    
 			if( !$row = $db->getRow($sql) ) GetItemPropsByCid($cid);  // 不存在则 调用类目API 并插入 
			if( $row = $db->getRow($sql) ){   
				if( strstr(addslashes($row['prop_name']),'颜色' ) ){ 
					$have_color = 1;
					 //求出颜色别名 
					 $prop_alias_t=explode(';', $prop_alias );  //得到别名数组 
					 foreach ( $prop_alias_t as $prop_alia){ 
						$prop_alia_t = explode(':', $prop_alia ); //一对别名数组  属性:属性值:别名   
						if( $prop_alia_t[1] == $prop_t[1] ){ 
							$row['name']=$prop_alia_t[2] ;//属性当中属性值 ==别名中属性值  则取出别名   
							break;
						}  
					 }     
					if( !$color_code = Check_is_exist('color','color_name',$row['name'],'','color_code') ){ //颜色不存则先插入
						$arr =array( 
						 			'color_name' =>$row['name'],
						 			'color_note' =>'0',
						 			'img_id' =>'0',
					 		);
					    OS_InsertIntoTB('color','color_name',$arr);
					    $color_id = Check_is_exist('color','color_name',$row['name'],'','color_id');
					    Update_table_key('color','color_code',$color_id," color_id='".$color_id."'"); 
					    Update_table_key('tb_guige1','color_code',$color_id, " cid='".$cid."' and vid='".$prop_t[1]."'");  //新插入后也可更新关联
					}else { ////颜色存则更新关联 
						 Update_table_key('tb_guige1','color_code',$color_code, " cid='".$cid."' and vid='".$prop_t[1]."'"); 
					}   
				 	if( ( $color_id = Check_is_exist('color','color_name',$row['name'],'','color_id')) && $goods_id){
				 		$arr =array( 
						 			'goods_id' => $goods_id,
						 			'color_id' => $color_id ,
						 			'color_name' => Check_is_exist('color','color_id',$color_id,'','color_name'),
						 			'img_id' =>'0',
						 			'goods_sn' => Check_is_exist('goods','goods_id',$goods_id,'','goods_sn'),
						 			'color_code' => Check_is_exist('color','color_id',$color_id,'','color_code'),
					 		  );
				 		OS_InsertIntoTB('goods_color','goods_id',$arr," color_id='".$color_id."'"); //向open_goods_color表中插入 商品的颜色* 
				 	}  
			 } elseif( strstr(addslashes($row['prop_name']),'尺码' ) ||  strstr(addslashes($row['prop_name']),'尺寸' )){
			 	     $have_size = 1;
					 //求出尺码别名
					 $prop_alias_t=explode(';', $prop_alias );  //得到别名数组 
					 foreach ( $prop_alias_t as $prop_alia){ 
						$prop_alia_t = explode(':', $prop_alia ); //一对别名数组  属性:属性值:别名   
						if( $prop_alia_t[1] == $prop_t[1] ){  
							$row['name']=$prop_alia_t[2] ;//属性当中属性值 ==别名中属性值  则取出别名   
							break;
						}  
					 }  
					 if( !$size_code = Check_is_exist('size','size_name',$row['name'],'','size_code') ){ // 不存则先插入
						 $arr =array( 
									'size_name' =>$row['name'],
									'size_note' =>'0' 
							);
							OS_InsertIntoTB('size','size_name',$arr);
							$size_id = Check_is_exist('size','size_name',$row['name'],'','size_id');
							Update_table_key('size','size_code',$size_id," size_id='".$size_id."'"); 
						    Update_table_key('tb_guige2','size_code',$size_id, " cid='".$cid."' and vid='".$prop_t[1]."'");  //新插入后也可更新关联
					 }else { ////颜色存则更新关联
						 Update_table_key('tb_guige2','size_code',$size_code, " cid='".$cid."' and vid='".$prop_t[1]."'"); 
					 }  
					 if( ( $size_id = Check_is_exist('size','size_name',$row['name'],'','size_id')) && $goods_id){
						$arr =array( 
									'goods_id' => $goods_id,
									'size_id' => $size_id ,
									'size_name' => Check_is_exist('size','size_id',$size_id,'','size_name'), 
									'goods_sn' => Check_is_exist('goods','goods_id',$goods_id,'','goods_sn'),
									'size_code' => Check_is_exist('size','size_id',$size_id,'','size_code'),
							  );
						OS_InsertIntoTB('goods_size','goods_id',$arr," size_id='".$size_id."'"); //向open_goods_size表中插入 商品的尺码* 
					} 
				} 
			} 
		}//end foreach
		if($have_color == 0 ){    //属性当中不当有颜色 则向goods_color表中插入均色 
			keepguige();
		    $color_id  =  Check_is_exist('color','color_code','000','','color_id') ;
			$arr=array(
				  'goods_id' => $goods_id,
				  'color_id' => $color_id ,
				  'color_name' =>'均色', 
				  'img_id'   =>'0',
				  'goods_sn' =>  Check_is_exist('goods','goods_id',$goods_id,'','goods_sn') ,
				  'color_code' =>'000',
				 );
			 OS_InsertIntoTB('goods_color','goods_id',$arr," color_id='".$color_id."'");  		
			}
		if($have_size == 0 ){    //属性当中不当有尺码 则 向goods_size表中插入均码 
		    keepguige();
		    $size_id  =  Check_is_exist('size','size_code','000','','size_id') ;
			$arr=array(
				  'goods_id' => $goods_id,
				  'size_id' => $size_id ,
				  'size_name' =>'均码', 
				  'goods_sn' => Check_is_exist('goods','goods_id',$goods_id,'','goods_sn') ,
				  'size_code' =>'000',  
				 );
			OS_InsertIntoTB('goods_size','goods_id',$arr," size_id='".$size_id."'");  		
		   } 
    }  
    /**
     * sku转成商品库存并关联　goods_color  goods_size
     * 
     * */
    function sku2inventory($goods_id, $iid,$cid  ){ 
    		global $_CFG, $exc,$db,$os,$topParamArr;    
    	    if( !$sku_id = Check_is_exist('tb_sku','iid',$iid,'','sku_id' ) )  GetInsertIntoSKUByIid($iid);  //sku_id不存在则调用taobao api
    	    $sku_rows = $db->getAll("select * from open_tb_sku where iid='".$iid."'");   
     		if( is_array($sku_rows) && $sku_rows[0] ){    // 存在 
    			 foreach ( $sku_rows as $sku_row){
				    			$properties = $sku_row['properties'];
				    			$properties_a = explode(';', $properties );   
				    			if( is_array($properties_a) && $properties_a[1] ){
					    				foreach ($properties_a as $props ){
												$prop = explode(':', $props );  
												if(is_array($prop) && $prop[1] ){
													$sql="select * from open_tb_propvalue where vid='".$prop[1]."'";  
												    $pv_row = $db->getRow($sql); 
												    if( $pv_row &&  strstr( $pv_row['prop_name'],'颜色' )   ) {  //插入goods_color表　并  
												        if(!Check_is_exist('tb_guige1','vid',$pv_row['vid'],"cid ='".$cid."'"))  GetItemPropsByCid($cid); //不存在则请求类目值并插入数据库
												        $sql="select  c.color_id,g.goods_name,g.goods_sn,c.color_code from open_tb_guige1 as gg1  
												    	      left join open_color as c on c.color_code=gg1.color_code 
												    	      left join open_goods as g on g.goods_id = '".$goods_id."' 
												    	      where gg1.vid='".$pv_row['vid']."' and gg1.cid ='".$cid."' ";   
												    	 $color_row = $db->getRow($sql) ;
												    	 $color_id=$color_row['color_id'];
												    	 $color_code=$color_row['color_code'];
												    	 $goods_sn=$color_row['goods_sn'];
												    	 if( !$color_id ) die('颜色未自动关联上<br/>'.$sql) ;   
												    }  //end $pv_row 
													if ( $pv_row && ( strstr( $pv_row['prop_name'],'尺码' ) ||  strstr( $pv_row['prop_name'],'尺寸' ) )   ) { //插入goods_size表　 
													        $sql="select s.size_id,g.goods_name,g.goods_sn,s.size_code  from open_tb_guige2 as gg2 
													    	 	   left join open_size as s on s.size_code=gg2.size_code
													    	 	   left join open_goods as g on g.goods_id = '".$goods_id."' 
													    	       where gg2.vid='".$prop[1]."' and gg2.cid ='".$cid."' ";   
															$size_row = $db->getRow($sql) ;
															$size_id  = $size_row['size_id'];
															$size_code = $size_row['size_code'];
													        if( !$size_id ) die('尺码未自动关联上<br/>'.$sql);   
													} //end if
												} //end $prop[1] 
					    				 } //end foreach  $props 
					    			if($goods_id && $color_id && $size_id ){	//插入　open_goods_inventory 库存表
					    				$arr=array(
						    					'goods_id'=>$goods_id,
						    					'color_id'=>$color_id,
						    					'size_id'=> $size_id,
						    					'goods_number_actual'=>$sku_row['quantity'],
						    					'goods_number_available'=>$sku_row['quantity'],
						    					'goods_number_alert'=>'1',
						    					'SPDM'=>Check_is_exist('goods','goods_id',$goods_id,'','goods_sn')   , 
						    					'GG1DM'=>Check_is_exist('color','color_id',$color_id,'','color_code')   , 
						    					'GG2DM'=>Check_is_exist('size','size_id',$size_id,'','size_code')   , 
					    					);
					    			  OS_InsertIntoTB('goods_inventory','goods_id',$arr," color_id='".$color_id."' and size_id='".$size_id."'"  );
					    			} 
					    		} //end if
				    	} //end foreach $sku_row
    		}else {  //taobao上不存在suk表 则os中自动转成 均色 均码 
    				keepguige(); 
					$color_id = Check_is_exist('color','color_code','000','','color_id');   //均色ID
					$size_id =  Check_is_exist('size','size_code','000','','size_id');   //均码ID
					$goods_num= Check_is_exist('tb_item','iid',$iid,'','num');
					$arr=array(
								'color_id'  =>  $color_id,
								'size_id'   =>	$size_id,
								'goods_id' =>   $goods_id,
								'goods_number_actual' => $goods_num,
								'goods_number_available' =>$goods_num,
								'goods_number_alert' =>	'1', 
								'SPDM'   =>Check_is_exist('goods','goods_id',$goods_id,'','goods_sn'),
								'GG1DM'   =>'000',
								'GG2DM'   =>'000',
							); 
					OS_InsertIntoTB('goods_inventory','goods_id',$arr, " color_id='".$color_id."' and size_id='".$size_id ."'"); 	 
    		} 
    		
    		
    }
	/**
	 * 下载商品根据别名,自动匹配颜色尺码
	 * */
    function AutoExeGuige($goods_sn, $property_alias,$cid ){
    	global $_CFG, $exc,$db,$os,$topParamArr;  
    	  if( $property_alias  ){
		    	$guiges = explode(';', $property_alias );
		    	foreach ($guiges as $guige){
		    		$gg = explode(':', $guige );
		    		$pid = $gg[0];
		    		$vid = $gg[1];
		    		$alia_name=$gg[2];  
		    		$sql="select name from open_tb_itemprop where pid=".$pid ;
		    		$p_name = $db->getOne($sql);
		    		if ( strstr($p_name,"颜色") ) {//商品ID 类别ID 属性值ID
		    			$sql=" select g.goods_sn,g.goods_id,gc.color_name,c.color_id,c.color_code  from open_goods_color as gc
								left join open_goods as g on g.goods_id =gc.goods_id 
								left join open_color as c on c.color_id= gc.color_id 
								where g.goods_sn='".$goods_sn."' order by c.color_name desc";  
		    			$color_rows= $db->getAll($sql);
		    			foreach ( $color_rows as $color_row){  
		    				   //if( strstr($alia_name, $color_row['color_name'] ) ){ //完全匹配上则跳出 
							   if(  $alia_name == $color_row['color_name']  ){ //完全匹配上则跳出 
		    				   		$sql="update open_tb_guige1 as gg1 set gg1.color_code ='".$color_row['color_code']."' where  gg1.cid='".$cid."' and gg1.vid='".$vid."'" ; 
									$db->query( $sql );	  
									break; 
		    				   	} 
		    			} 
		    		}elseif (strstr($p_name,"尺码") || strstr($p_name,"尺寸")   ){  //商品ID 类别ID 属性值ID
		    			$sql ="select  g.goods_sn,g.goods_id,s.size_name,s.size_id,s.size_code  from open_goods_size as gs
							left join open_goods as g on g.goods_id =gs.goods_id 
							left join open_size as s on s.size_id= gs.size_id
							where g.goods_sn='".$goods_sn."' order by s.size_name desc"; 
		    			$size_rows= $db->getAll($sql);
		    			foreach ( $size_rows as $size_row){
		    				//if( strstr($alia_name, $size_row['size_name'] ) ){ //完全匹配上则跳出
							if( $alia_name==$size_row['size_name']  ){ //完全匹配上则跳出
		    					$sql="update open_tb_guige2 as gg2 set gg2.size_code ='".$size_row['size_code']."' where  gg2.cid='".$cid."' and gg2.vid='".$vid."'" ; 
								$db->query( $sql );	 
				    		     break; 
		    				} 
		    			}  
		    		}  
		    	} 
		    } 
    }

    
   /**
    * 省市县替换
    * */
    function str_replace_region($str){
    	$str=str_replace('省','',$str);
    	$str=str_replace('市','',$str);
    	$str=str_replace('县','',$str);
    	return  $str;
    }
     
	
/***********************************************strat 系统共用函数库***************************************************/ 	
	/**
	 * 定义taobao 相关API常量
	 * */
	function  defineAPI_APP() {
		global $_CFG ; 
		if(!defined('API_URL')) define('API_URL',  $_CFG['taobao_api_url']); 
		if(!defined('API_USER')) define('API_USER',  $_CFG['taobao_user']); 
		if(!defined('APP_KEY')) define('APP_KEY',   $_CFG['taobao_app_key'] ); 
		if(!defined('APP_SECRET')) define('APP_SECRET',   $_CFG['taobao_app_secret'] ); 
		if(!defined('API_SESSION')) define('API_SESSION',  $_CFG['taobao_sessionkey'] );
		if(!defined('APP_PWD')) define('APP_PWD', Check_is_exist('tb_app','nick',API_USER,'','password') );     
	} 
	/**
	 * 更新table表中x字段为y值
	 * */
	function Update_table_key($tableName,$field,$value,$where ,$retrun_field=''){
		global  $db,$os; 
		$sql="update ".$os->table($tableName) ." set ".$field ." = '".$value."'  where ".$where ; 
		$db->query($sql); 
		 admin_log($os->table($tableName).'[Update_table_key]更新成功'.$where , 'edit', 'top_api'); //编辑    淘宝表
		if($retrun_field) return Check_is_exist($tableName,$field,$value,$where,$retrun_field);
		return '';
	}
	/**
	 * 判断table表中的x字段是否存在y值 exist
	 * */
	function Check_is_exist($tableName,$field,$value,$where='',$retrun_field='id'){
		global  $db,$os;
		if( $where ) {
			$sql="select ".$retrun_field." from ".$os->table($tableName) ." where ".$field ." = '".$value."' and ".$where ; 
		}else {
			$sql="select ".$retrun_field." from ".$os->table($tableName) ." where ".$field ." = '".$value."'" ; 
		}    
		if( $id=$db->getOne($sql) ){  //存在
			 return  $id;
		}else { //不存在
			return '';
		}
	}
	/**
	 * 向OS_tb表中插入TOP下载的数据 (tb_name表名, key 主键)
	 * 并统一日志处理
	 **/
	function OS_InsertIntoTB($tableName,$key,$tableParamArr,$where='' )
	{ 
		global  $db,$os;
		if( $where ) 
		{
			$where =  $key." = '$tableParamArr[$key]' and ".$where ;   
		}
		else 
		{
			$where =  $key." = '$tableParamArr[$key]'";   
		}   
		$exc = new exchange($os->table($tableName), $db, 'id', $key); 
		if( !is_array($tableParamArr) )
		{
			return ;
		}
		$table = array();
		foreach ($tableParamArr as $_key => $_value )
		{
	    		 $table[$_key]=addslashes($_value);
	    }   
		if(!$exc->is_only($key,$tableParamArr[$key],'',$where) )
		{  
			if ($tableName!='tb_propvalue' && $tableName!= 'tb_guige1' && $tableName!= 'tb_guige2' && $tableName!= 'tb_itemprop'  && $tableName!='tb_sku'  && $tableName!= 'tb_ItemImg') 
			{
				$db->autoExecute($os->table($tableName), $table, 'UPDATE', $where );
				 admin_log($os->table($tableName).'[OS_InsertIntoTB]更新成功'.$where , 'edit', 'top_api'); //编辑    淘宝表
			} 
	    }
		else
		{  
	    	$db->autoExecute($os->table($tableName), $table, 'INSERT'); 
	    	admin_log($os->table($tableName).'[OS_InsertIntoTB]成功插入'.$where , 'add', 'top_api');   //添加 
	    } 
	}
    /**
	 * 调用taobao的 api并分页  并日志统一处理
	 * 27  Invalid session  会话期识别码无效  
	 * 26  Missing session  会话期识别码丢失   
	 * */
	function returnCallBackPage($client,$method,$key='')
	{
		//echo $method.'</br>';
	 	$result = $client->$method();    			//xml 
	    $result = taobao_api::getXmlData($result);  //解释XML文件  
	    if($result[code])
		{//写出错日志  
	         admin_log( 'taobao.'.$method.'方法请求失败!'.':['.$result[code].']'.$result[msg].serialize($client) , 'post', 'top_api'); 
	         if( $result[code] ==27  ||  $result[code] ==26 ||  $result[code] ==25   )
			 {//echo ('会话期识别码无效 或 会话期识别码丢失'); 
	         		LoginTaoBao(API_USER , APP_PWD); 
	         }
	    	 return $result;
	    }
		else 
		{//写正确日志 
	        admin_log('taobao.'.$method.'方法成功!'.serialize($client), 'post', 'top_api');
	        if($key) 
			{
				$result = taobao_api::getXmlPageData( $result ,$key );  //解释XML文件并分页
			}
	    	return $result;
	    } 	
	} 
	
	function parseurl($url="")
	{
		$url = rawurlencode(mb_convert_encoding($url, 'gb2312', 'utf-8'));
		$a = array("%3A", "%2F", "%40");
		$b = array(":", "/", "@");
		$url = str_replace($a, $b, $url);
		return $url;
	} 


	/**
	 * 设置用户输入参数 
	 * */
	function setUserParameter($client,$userParamArr){ 
		 foreach ($userParamArr as $key => $value ){
	    	$client->setParameter($key,$value); 
	    }
	}
	/**
	 * 返回分页后的list数组
	 */
 	 function lib_getArray_params_page($paramArr,$key){
		//调用taobao的api返回结果
		$result = taobao_api::postResult($paramArr);  
		//解析xml结果
		$result = taobao_api::getXmlData($result); 
		//解析分页功能
		return  taobao_api::getXmlPageData($result,$key);  
  	}
	/**
	 * 返回taobao的数组
	 */
  	function lib_getArray_params($paramArr){
		//调用taobao的api返回结果
		$result = taobao_api::postResult($paramArr);  
		//解析xml结果
		$result = taobao_api::getXmlData($result);  
		return 	 $result;
  }
/***********************************************end 系统共用函数库***************************************************/ 	 
	function GetCurUrl(){
		if(!empty($_SERVER["REQUEST_URI"])){
			$scriptName = $_SERVER["REQUEST_URI"];
			$nowurl = $scriptName;
		}else{
			$scriptName = $_SERVER["PHP_SELF"];
			if(empty($_SERVER["QUERY_STRING"])) $nowurl = $scriptName;
			else $nowurl = $scriptName."?".$_SERVER["QUERY_STRING"];
		}
		return $nowurl;
	}
 /**
     * 
     *  通过向淘宝服务器post数据，实现自动登录，支持中文用户名
     * */
    function LoginTaoBao($username, $password ){  
    	global $_CFG ; 
    	$username = urlencode(iconv("UTF-8","GB2312",$username)); //"优衣派服饰专营店"; // 九牧王官方旗舰" ;
		$password = urlencode(iconv("UTF-8","GB2312",$password)); //"joeone_999" ; 
		/*********  by winner ADD  09-12-13 土登陆方法  。   ********/  
		if( $_CFG['taobao_api_url']=='http://gw.api.taobao.com/router/rest'  ){ //正式环境
			$url_a="http://member1.taobao.com/member/login.jhtml?TPL_username=".$username."&TPL_password=".$password."&Submit=%b5%c7%c2%bc&actionForStable=enable_post_user_action&action=Authenticator&TPL_redirect_url=_oooo_&event_submit_do_login=anything&abtest=&pstrong=3&from=&yparam=&done=";
			$url="http://container.open.taobao.com/container?appkey=".APP_KEY;
	        echo ("<script>window.open('".$url_a."'); window.opener = null;window.close(); </script>") ;  //url到一件页面   	
		}else {  
				include_once('Snoopy.class.php');
				$snoopy = new Snoopy;  
				$formurl = "http://open.taobao.com/isv/authorize.php?appkey=".APP_KEY;
				$formvars = array();
				$formvars['zhxz'] = '2';  //用户自定义
				$formvars['nick'] = API_USER ;   
				$formvars['url'] = str_replace('sources/','',$_CFG['pre_fetch_img'])."/includes/modules/taobao.api/top_return_call.php";
			    $snoopy -> submit($formurl,$formvars);
				$res = preg_match_all("/value=.*style=/",htmlentities($snoopy -> results),$matches);  
				$authcode = $matches[0][0];
				$authcode = substr($authcode, 12);
				$authcode = substr($authcode, 0, -13);
				//更新此用户的受权码
				Update_table_key('shop_config','value',$authcode," code='".taobao_app_secret."'");
				Update_table_key('tb_app','app_secret',$authcode," nick='".API_USER."' and app_key='".APP_KEY."' ");
				clear_cache_files();  /* 清除缓存 */  
			    //$url_a="http://member1.tbsandbox.com/member/login.jhtml?TPL_username=".$username."&TPL_password=".$password."&Submit=%b5%c7%c2%bc&actionForStable=enable_post_user_action&action=Authenticator&TPL_redirect_url=_oooo_&event_submit_do_login=anything&abtest=&pstrong=3&from=&yparam=&done=";
		        $url="http://container.api.tbsandbox.com/container?authcode=".$authcode ; 
		}   
		echo ("<script>window.open('".$url."'); </script>") ;  //url到一件页面 
		return ;
		/*********  by winner ADD  09-12-13 土登陆方法哈 。   ********/ 
//		$curl = new curl(); 
//		$curl->loginUrl = 'http://member1.taobao.com/member/login.jhtml';
//		$userInfo = new stdClass();
//		$userInfo->username = $username ;
//		$userInfo->password = $password ;
//		$curl->data = $userInfo;
//		$curl->curlPost();
//		echo $curl->fetchUrl('http://member1.taobao.com/member/login.jhtml');
//    	die(); 
		$url="http://member1.taobao.com/member/login.jhtml";
    	$useLoginParamArr = array(
						'TPL_username'=> $username,
						'TPL_password'=> $password,
						'Submit'=> '登录',
						'actionForStable'=> 'enable_post_user_action',
						'action'=> 'Authenticator',
						'TPL_redirect_url'=>  '_oooo_',
    				    'event_submit_do_login'=>  'anything',
						'abtest'=> 'pstrong' 
	     	);   
	    $result = taobao_api::postResult($useLoginParamArr,$url); 	
	    print_r($result);
	    die();
	  
	    
//	    $formurl ="http://member1.taobao.com/member/login.jhtml?TPL_username=%d3%c5%d2%c2%c5%c9%b7%fe%ca%ce%d7%a8%d3%aa%b5%ea&TPL_password=xin894774212wu&Submit=%b5%c7%c2%bc&actionForStable=enable_post_user_action&action=Authenticator&TPL_redirect_url=_oooo_&event_submit_do_login=anything&abtest=&pstrong=3&from=&yparam=&done=";   //http://member1.taobao.com/member/login.jhtml
//		$snoopy = new Snoopy;    
//		//$snoopy -> submit($formurl);
//		$snoopy->fetch($formurl);
//	    echo $snoopy->results ; 
    }	

		
	
		

	






	


























	







?>